package com.yinshan.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yinshan.dialog.adapter.KeyBoardAdapter;
import com.yinshan.dialog.utils.AttrsUtils;
import com.yinshan.dialog.widget.SeparatedEditText;

import cn.cloudcore.iprotect.CPayEditText;
import cn.cloudcore.iprotect.callback.CStateCallback;
import cn.cloudcore.iprotect.plugin.CEditTextAttrSet;

/**
 * @author limh
 * @function
 * @date 2019/1/28 14:46
 */
public class NumKeyDialog extends Dialog {
    private static String TAG = "NumKeyDialog";
    public static int TYPE_PASS = 1;
    public static int TYPE_PHONE = 2;
    public static int TYPE_CODE = 3;

    public NumKeyDialog(@NonNull Context context) {
        super(context, R.style.styleDialog);
    }

    public static class Builder {
        private Context context;
        private int type;
        private String phone;
        private boolean isOutTouchCancel;
        private OnClickListener leftOnClickListener;
        private OnClickListener rightOnClickListener;
        private NumKeyDialog.Builder.OnTextResultListener onTextResultListener;

        private LinearLayout linePhone;
        private LinearLayout lineHandle;
        private SeparatedEditText editPass;
        private CPayEditText ceditPass;
        private GridView gridKey;
        private EditText editPhone;
        private TextView txtTitle;
        private Button btnTop;
        private Button btnLeft;
        //短信验证是否隐藏
        private boolean checkPhone = false;
        //隐藏中间忘记密码和短信验证功能
        private boolean noHandle = false;
        //是否使用加密键盘
        private boolean useThirdKeyboard = false;
        private String sm2PublicKey = "";

        public Builder(Context context) {
            this.type = NumKeyDialog.TYPE_PASS;
            this.isOutTouchCancel = false;
            this.context = context;
        }

        public Builder setType(int type) {
            this.type = type;
            return this;
        }

        public NumKeyDialog.Builder setOutTouchCancel(boolean outTouchCancel) {
            this.isOutTouchCancel = outTouchCancel;
            return this;
        }

        public Builder setPhone(String phone) {
            this.phone = phone;
            return this;
        }

        public Builder setCheckPhone(boolean checkPhone) {
            this.checkPhone = checkPhone;
            return this;
        }

        public Builder setNoHandle(boolean noHandle) {
            this.noHandle = noHandle;
            return this;
        }

        public Builder setEncryptKeyboard(boolean useThirdKeyboard, String sm2PublicKey) {
            this.useThirdKeyboard = useThirdKeyboard;
            this.sm2PublicKey = sm2PublicKey;
            return this;
        }

        public NumKeyDialog.Builder setOnTextResultListener(NumKeyDialog.Builder.OnTextResultListener onTextResultListener) {
            this.onTextResultListener = onTextResultListener;
            return this;
        }

        public NumKeyDialog.Builder setLeftOnClickListener(OnClickListener leftOnClickListener) {
            this.leftOnClickListener = leftOnClickListener;
            return this;
        }

        public NumKeyDialog.Builder setRightOnClickListener(OnClickListener rightOnClickListener) {
            this.rightOnClickListener = rightOnClickListener;
            return this;
        }

        public NumKeyDialog create() {
            LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (null == inflater) {
                Log.e(NumKeyDialog.TAG, "dialog create is fail,inflater is null");
                return null;
            } else {
                return this.createMsgDialog(inflater.inflate(R.layout.layout_dialog_numkey, null));
            }
        }

        private NumKeyDialog createMsgDialog(View layout) {
            final NumKeyDialog msgDialog = new NumKeyDialog(this.context);
            msgDialog.addContentView(layout, new ViewGroup.LayoutParams(-1, -1));
            msgDialog.setCanceledOnTouchOutside(this.isOutTouchCancel);
            editPhone = layout.findViewById(R.id.edit_phone);
            linePhone = layout.findViewById(R.id.line_phone);
            lineHandle = layout.findViewById(R.id.line_handle);
            editPass = layout.findViewById(R.id.edit_pass);
            ceditPass = layout.findViewById(R.id.cedit_pass);
            gridKey = layout.findViewById(R.id.grid_dg);
            txtTitle = layout.findViewById(R.id.txt_dg_title);
            btnTop = layout.findViewById(R.id.btn_dg_top);
            btnLeft = layout.findViewById(R.id.btn_dg_left);
            Button btnRight = layout.findViewById(R.id.btn_dg_right);
            Window window = msgDialog.getWindow();
            if (null != window) {
                android.view.WindowManager.LayoutParams params = window.getAttributes();
                Point point = new Point();
                Display display = ((Activity) this.context).getWindowManager().getDefaultDisplay();
                display.getSize(point);
                params.width = point.x;
                window.setGravity(Gravity.BOTTOM);
                window.setAttributes(params);
            }
            layout.findViewById(R.id.img_dg_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (msgDialog.isShowing()) {
                        msgDialog.dismiss();
                    }
                    if (useThirdKeyboard) {
                        ceditPass.hideCKeyboardView();
                    }
                }
            });
            this.hideSoftInput();
            btnRight.setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != Builder.this.rightOnClickListener) {
                        Builder.this.rightOnClickListener.onClick(msgDialog, -1);
                    }
                }
            });
            btnTop.setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if (Builder.this.type == NumKeyDialog.TYPE_PASS) {
                            Builder.this.onTextResultListener.OnTextResult(Builder.this, useThirdKeyboard ? ceditPass.getValue("" + System.currentTimeMillis()) : editPass.getText().toString().trim(), NumKeyDialog.TYPE_PASS);
                        } else if (Builder.this.type == NumKeyDialog.TYPE_PHONE) {
                            Builder.this.onTextResultListener.OnTextResult(Builder.this, editPhone.getText().toString().trim(), NumKeyDialog.TYPE_PHONE);
                            Builder.this.type = NumKeyDialog.TYPE_CODE;
                        } else {
                            Builder.this.onTextResultListener.OnTextResult(Builder.this, useThirdKeyboard ? ceditPass.getValue("" + System.currentTimeMillis()) : editPass.getText().toString().trim(), NumKeyDialog.TYPE_CODE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            if (checkPhone) {
                btnLeft.setVisibility(View.INVISIBLE);
            } else {
                btnLeft.setVisibility(View.VISIBLE);
            }
            if (noHandle) {
                lineHandle.setVisibility(View.GONE);
            } else {
                lineHandle.setVisibility(View.VISIBLE);
            }
            if (useThirdKeyboard) {
                editPass.setVisibility(View.GONE);
                ceditPass.setVisibility(View.VISIBLE);
                final CEditTextAttrSet attrSet = AttrsUtils.getNumberAttrSet("numkey_dialog");
                attrSet.clearWhenOpenKbd = true;
                attrSet.outsideClose = true;
                ceditPass.initialize(attrSet, new CStateCallback() {
                    @Override
                    public void onStateChanged(int i) {

                    }

                    @Override
                    public void onUpdate(String s, int i, char c) {

                    }

                    @Override
                    public boolean onFinish() {
                        return false;
                    }
                }, R.drawable.shape_pay_password_bg, 6, Color.parseColor("#333333"), 4, 1f, Color.parseColor("#CCCCCC"));
                AttrsUtils.setOneLayerCipher(ceditPass, sm2PublicKey);
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) gridKey.getLayoutParams();
                lp.bottomMargin = getScreenHeight() - dp2px(220);
                gridKey.setLayoutParams(lp);
                ceditPass.performClick();
                gridKey.setVisibility(View.INVISIBLE);
                btnTop.setEnabled(true);
            } else {
                editPass.setVisibility(View.GONE);
                ceditPass.setVisibility(View.VISIBLE);
            }
            btnLeft.setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Builder.this.type == NumKeyDialog.TYPE_PASS) {
                        Builder.this.type = NumKeyDialog.TYPE_PHONE;
                    } else {
                        Builder.this.type = NumKeyDialog.TYPE_PASS;
                    }
                    updateView();
                    if (null != Builder.this.leftOnClickListener) {
                        Builder.this.leftOnClickListener.onClick(msgDialog, -2);
                    }
                }
            });
            editPass.setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Builder.this.hideSoftInput();
                }
            });
            editPass.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (Builder.this.type == NumKeyDialog.TYPE_PASS && !useThirdKeyboard) {
                        if (editPass.length() == 6) {
                            btnTop.setEnabled(true);
                        } else {
                            btnTop.setEnabled(false);
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });
            editPhone.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (Builder.this.type == NumKeyDialog.TYPE_PHONE) {
                        if (editPhone.length() == 11) {
                            btnTop.setEnabled(true);
                        } else {
                            btnTop.setEnabled(false);
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable editable) {
                }
            });
            gridKey.setHorizontalSpacing(1);
            gridKey.setVerticalSpacing(1);
            gridKey.setBackgroundColor(Color.parseColor("#CCCCCC"));
            final KeyBoardAdapter keyAdapter = new KeyBoardAdapter(this.context);
            gridKey.setAdapter(keyAdapter);
            gridKey.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (Builder.this.type != NumKeyDialog.TYPE_PASS && Builder.this.type != NumKeyDialog.TYPE_CODE) {
                        if (!TextUtils.isEmpty(keyAdapter.getKeys().get(position)) && !"x".equals(keyAdapter.getKeys().get(position))) {
                            editPhone.setText(String.format("%s%s", editPhone.getText().toString().trim(), keyAdapter.getKeys().get(position)));
                        }

                        if ("x".equals(keyAdapter.getKeys().get(position)) && editPhone.getText().length() > 0) {
                            editPhone.setText(editPhone.getText().subSequence(0, editPhone.getText().length() - 1));
                        }

                        editPhone.setSelection(editPhone.length());
                    } else {
                        if (!TextUtils.isEmpty(keyAdapter.getKeys().get(position)) && !"x".equals(keyAdapter.getKeys().get(position))) {
                            editPass.setText(String.format("%s%s", editPass.getText().toString().trim(), keyAdapter.getKeys().get(position)));
                        }

                        if ("x".equals(keyAdapter.getKeys().get(position)) && editPass.getText().length() > 0) {
                            editPass.setText(editPass.getText().subSequence(0, editPass.getText().length() - 1));
                        }
                    }

                }
            });
            updateView();
            msgDialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    Log.d(TAG, "关闭键盘");
                    if (useThirdKeyboard) {
                        ceditPass.clear();
                        ceditPass.hideCKeyboardView();
                    }
                }
            });
            return msgDialog;
        }

        private void hideSoftInput() {
            InputMethodManager inputManager = (InputMethodManager) this.context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (null != inputManager) {
                inputManager.toggleSoftInput(0, 2);
            }

        }

        private void updateView() {
            if (Builder.this.type != NumKeyDialog.TYPE_PASS && Builder.this.type != NumKeyDialog.TYPE_CODE) {
                linePhone.setVisibility(View.VISIBLE);
                if (useThirdKeyboard) {
                    ceditPass.setVisibility(View.GONE);
                    gridKey.setVisibility(View.VISIBLE);
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) gridKey.getLayoutParams();
                    lp.bottomMargin = 0;
                    gridKey.setLayoutParams(lp);
                } else {
                    editPass.setVisibility(View.GONE);
                }
                editPhone.setText(phone);
                editPhone.setEnabled(false);
                txtTitle.setText("请输入手机号");
                btnTop.setText("获取验证码");
                btnLeft.setText("密码支付");
            } else {
                linePhone.setVisibility(View.GONE);
                if (useThirdKeyboard) {
                    ceditPass.setVisibility(View.VISIBLE);
                    gridKey.setVisibility(View.INVISIBLE);
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) gridKey.getLayoutParams();
                    lp.bottomMargin = getScreenHeight() - dp2px(220);
                    gridKey.setLayoutParams(lp);
                } else {
                    editPass.setVisibility(View.VISIBLE);
                }
                editPass.clearText();
                txtTitle.setText("请输入支付密码");
                btnTop.setText("确定");
                btnLeft.setText("短信验证码支付");
            }
        }

        public void setInputCode() {
            if (null != linePhone) {
                linePhone.setVisibility(View.GONE);
            }
            if (null != editPass) {
                editPass.clearText();
                editPass.setVisibility(View.VISIBLE);
            }
            if (null != txtTitle) {
                txtTitle.setText("请输入验证码");
            }
            if (null != btnTop) {
                btnTop.setText("确定");
            }
            if (null != btnLeft) {
                btnLeft.setText("密码支付");
            }
        }

        public void checkPhone() {
            try {
                if (null != btnLeft) {
                    btnLeft.post(new Runnable() {
                        @Override
                        public void run() {
                            btnLeft.performClick();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public interface OnTextResultListener {
            void OnTextResult(Builder builder, String result, int type);
        }

        private int dp2px(float dipValue) {
            final float scale = Resources.getSystem().getDisplayMetrics().density;
            return (int) (dipValue * scale + 0.5f);
        }

        private int getScreenHeight() {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metrics);
            double baseHeight = metrics.widthPixels * 4 / 10 / 0.6429f;
            return (int) (baseHeight + baseHeight / 4 * 2 / 3);
        }
    }
}
